package cn.swing.ushare.article.webapi.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.URLUtil;

import cn.swing.ushare.article.webapi.mapper.ArticleMapper;
import cn.swing.ushare.common.ex.ServiceException;
import cn.swing.ushare.common.restful.JsonPage;
import cn.swing.ushare.common.web.State;
import cn.swing.ushare.pojo.dto.ArticleAddNewDTO;
import cn.swing.ushare.pojo.dto.ArticlePictureAddDTO;
import cn.swing.ushare.pojo.entity.Article;
import cn.swing.ushare.pojo.entity.ArticlePicture;
import cn.swing.ushare.pojo.entity.Category;
import cn.swing.ushare.pojo.vo.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import cn.swing.ushare.article.service.IArticleService;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;

@Service
public class ArticleServiceImpl implements IArticleService {

    String dirPath = null;


    @Autowired
    private ArticleMapper articleMapper;

    /**
     * *********************************** insert **********************************************************************
     */
    //添加类别
    @Override
    public int insertCategory(Category category) {
        articleMapper.insertOperationLog("分类管理", "新增",
                logOperation(), "新增类别:'" + category.getName() + "'");
        return articleMapper.insertCategory(category);
    }

    //存放文章图片
    @Override
    public int insertArticlePictures(ArticlePicture articlePicture) {
        return articleMapper.insertArticlePictures(articlePicture);
    }

    //插入用户发布的文章
    @Override
    public int insertArticle(Article article) {
//        article.setUserId(Integer.valueOf(logOperation().substring(2)));
        return articleMapper.insertArticle(article);
    }

    /**
     * *********************************** delete **********************************************************************
     */

    //根据id删除文章
    @Override
    public int deleteArticleById(Long id) {
        String operateArticle = articleMapper.selectTitleById(id);
        int rows = articleMapper.deleteArticleById(id);
        if (rows == 0) {
            throw new ServiceException(State.ERR_ARTICLE_DELETE, "删除失败,文章不存在");
        } else {
            Long[] ids = new Long[1];
            ids[0] = id;
            articleMapper.deleteCommentByArticleIds(ids);
            articleMapper.insertOperationLog("文章列表", "删除",
                    logOperation(), "删除标题为:[" + operateArticle + "]的文章!");
        }
        return rows;
    }

    //批量删除文章
    @Override
    public int batchDeleteArticleByIds(Long[] ids) {
        List<String> titles = new ArrayList<>();
        for (Long id : ids) {
            titles.add(articleMapper.selectTitleById(id));
        }
        Integer rows = articleMapper.batchDeleteArticleById(ids);
        if (rows == 0) {
            throw new ServiceException(State.ERR_ARTICLE_DELETE, "删除失败,文章不存在");
        } else {
            articleMapper.deleteCommentByArticleIds(ids);
            for (String title : titles) {
                articleMapper.insertOperationLog("文章列表", "删除", logOperation(), "删除标题为: [" + title + "]的文章");
            }
            return rows;
        }


    }

    //根据id删除类别
    @Override
    public int deleteCategoryById(Long id) {

        articleMapper.insertOperationLog("分类管理", "删除",
                logOperation(), "删除类别:'" + articleMapper.selectCategoryById(id) + "'");
        return articleMapper.deleteCategoryById(id);
    }

    //批量删除类别
    @Override
    public int batchDeleteCategoryById(Long[] ids) {
        List<String> categories = new ArrayList<>();
        for (Long id : ids) {
            categories.add(articleMapper.selectCategoryById(id));
        }

        Integer rows = articleMapper.batchDeleteArticleById(ids);
        if (rows == 0) {
            throw new ServiceException(State.ERR_CATEGORY_NOT_FOUND, "删除失败,类别不存在");
        } else {
            for (String category : categories) {
                articleMapper.insertOperationLog("分类管理", "删除",
                        logOperation(), "删除类别:'" + category + "'");
            }
            return rows;
        }
    }


    /**
     * *********************************** select **********************************************************************
     */

    //查询所有文章类别
    @Override
    public List<CategorySimpleVO> selectSimpleCategory(Integer current) {
        return articleMapper.selectSimpleCategory(current);
    }

    //根据类别名称查询类别
    @Override
    public List<CategorySimpleVO> selectSimpleCategoryByName(Integer currentPage, String categoryName) {
        return articleMapper.selectSimpleCategoryByName(currentPage, categoryName);
    }

    @Override
    public List<CategorySimpleVO> selectSimpleCategoryList(Integer currentPage) {
        return articleMapper.selectSimpleCategoryList(currentPage);
    }

    //查询根据当前条件分类的总条数
    @Override
    public Integer selectCategoryCount(String categoryName) {
        return articleMapper.selectCategoryCount(categoryName);
    }

    @Override
    public Integer countAllArticle() {
        return articleMapper.countAllArticle();
    }


    @Override
    public List<ArticleTopSimpleVO> topTenList() {
        return articleMapper.topTenList();
    }


    //查询数据库所有文章
    //@Override
    //public List<ArticleDetailsVO> selectArticleDetails() {
    //    return articleMapper.selectArticles(current);
    //}


    //根据文章状态查询文章
    @Override
    public List<ArticleDetailsVO> selectArticleByState(Long state) {
        return articleMapper.selectArticleByState(state);
    }

    //根据文章状态查询文章

    @Override
    public List<ArticleDetailsVO> selectArticleByType(Integer type) {
        return articleMapper.selectArticleByType(type);
    }


    @Override
    public List<ArticleSimpleVO> selectArticleCollectionByUserId(Integer userId) {
        return articleMapper.selectArticleCollectionByUserId(userId);
    }

    //查询所有文章类别
//    @Override
//    public List<CategorySimpleVO> selectSimpleCategory(Integer current) {
//        return articleMapper.selectSimpleCategory(current);
//    }

    //根据类别名称查询类别
    @Override
    public List<CategorySimpleVO> selectSimpleCategoryByName(String name) {
        return articleMapper.selectSimpleCategoryByName(name);
    }

    //根据文章id查询文章
    @Override
    public List<ArticleDetailsVO> selectArticleByCategoryId(Integer categoryId) {
        return articleMapper.selectArticleByCategoryId(categoryId);
    }

    //根据文章标题查询文章
    @Override
    public List<ArticleDetailsVO> selectArticleByTitle(String title, Integer currentPage) {
        return articleMapper.selectArticleByTitle(title, currentPage);
    }

    @Override
    public ArticleDetailsVO selectArticleDetailsById(Integer id) {
        return articleMapper.selectArticleDetailsById(id);
    }

    @Override
    public List<String> selectArticlePicturesById(Integer id) {
        return articleMapper.selectArticlePicturesById(id);
    }

    @Override
    public List<ArticleSimpleVO> selectArticleSimpleById(Integer id) {
        return articleMapper.selectArticleSimpleById(id);
    }

    //查询文章显示到文章首页
    @Override
    public List<ArticleHomeVO> selectArticleHome() {
        String username = logOperation();
        List<Integer> categoryId = new ArrayList<>();
        if (!(username.equals("anonymousUser"))) {
            Integer userId = Integer.valueOf(username.substring(2));
            categoryId = articleMapper.selectCategoryIdByUserId(userId);
        }
        List<ArticleHomeVO> list = new ArrayList<>();
        List<ArticleHomeVO> listHome = selectArticleHomePart(categoryId);
        List<ArticleHomeVO> listHomeRand = selectArticleHomeRandPart();

        list.addAll(listHome);
        list.addAll(listHomeRand);
        Collections.shuffle(list);

        return list;
    }

    //查询文章显示到文章首页
    public List<ArticleHomeVO> selectArticleHomePart(List<Integer> categoryId) {
        System.out.println("ArticleServiceImpl.selectArticleHome");
        System.out.println(articleMapper.selectArticleHome(categoryId));
        return articleMapper.selectArticleHome(categoryId);

    }

    //查询文章显示到文章首页
    public List<ArticleHomeVO> selectArticleHomeRandPart() {
        return articleMapper.selectArticleHomeRand();
    }

    //查询热门文章
    @Override
    public List<ArticleHomeVO> selectHotArticle() {
        return articleMapper.selectHotArticle();
    }

    @Override
    public Integer selectIsLovedByUserIdAndArticleId(Integer articleId, Integer userId) {
        return articleMapper.selectIsLovedByUserIdAndArticleId(articleId, userId);
    }

    @Override
    public Integer deleteIsLovedByUserIdAndArticleId(Integer articleId, Integer userId) {
        return articleMapper.deleteIsLovedByUserIdAndArticleId(articleId, userId);
    }

    @Override
    public Integer insertIsLovedByUserIdAndArticleId(Integer articleId, Integer userId) {
        return articleMapper.insertIsLovedByUserIdAndArticleId(articleId, userId);
    }

    @Override
    public Integer addArticleLoveCountById(Integer id) {
        return articleMapper.addArticleLoveCountById(id);
    }

    @Override
    public Integer subArticleLoveCountById(Integer id) {
        return articleMapper.subArticleLoveCountById(id);
    }

    @Override
    public Integer addArticleCollection(Integer articleId, Integer userId) {
        return articleMapper.addArticleCollection(articleId, userId);
    }

    @Override
    public Integer deleteArticleCollection(Integer articleId, Integer userId) {
        return articleMapper.deleteArticleCollection(articleId, userId);
    }

    @Override
    public Integer selectArticleCollectionStatus(Integer articleId, Integer userId) {
        return articleMapper.selectArticleCollectionStatus(articleId, userId);
    }

    @Override
    public Integer addArticleCollectionCounts(Integer id) {
        return articleMapper.addArticleCollectionCounts(id);
    }

    @Override
    public Integer subArticleCollectionCounts(Integer id) {
        return articleMapper.subArticleCollectionCounts(id);
    }

    //查询文章显示到前台频道

    @Override
    public List<ArticleHomeVO> selectArticleToChannel(Integer categoryId, Integer sortId) {
        return articleMapper.selectArticleToChannel(categoryId, sortId);
    }

    @Override
    public List<ArticleHomeVO> selectArticleToRecommend(Integer categoryId) {
        return articleMapper.selectArticleToRecommend(categoryId);
    }


    @Override
    public List<ArticleDetailsVO> getAllArticles(Integer page, Integer index, Integer type, Integer category) {
        List<ArticleDetailsVO> list = articleMapper.selectArticles(page, index, type, category);
        return list;
    }


    @Override
    public Integer articlesCount(Integer index, Integer type, Integer category) {
        return articleMapper.articlesCount(index, type, category);
    }


    @Override
    public Integer addArticleViews(Integer id) {
        return articleMapper.addArticleViews(id);
    }

    //查询当前用户发表的最新的文章
    @Override
    public Integer selectCurrentUserNewArticle(Integer userId) {
        return articleMapper.selectCurrentUserNewArticle(userId);
    }

    @Override
    public List<ArticleResultVO> searchArticles(String keyword, Integer page) {
        return articleMapper.searchArticles(keyword, page);
    }

    @Override
    public Integer getSearchCounts(String keyword) {
        return articleMapper.getSearchCounts(keyword);
    }

    //上传图片
    @Override
    public String uploadPictures(MultipartFile picFile) throws Exception {
        //得到保存文章图片文件夹的相对路径
        //getURL(File file)
        //获得URL，常用于使用绝对路径时的情况
        //file(String path)
        //创建File对象，自动识别相对或绝对路径，相对路径将自动从ClassPath下寻找
        String urlStr = URLUtil.getURL(FileUtil.file("articlePictures")).toString();
        System.out.println("urlStr = " + urlStr);
        //urlStr = file:/D:/Danei/ushare-management/ushare-article/ushare-article-webapi/target/classes/articlePictures
        dirPath = urlStr.substring(urlStr.indexOf("ushare-management"), urlStr.indexOf("ushare-article"));
        //dirPath = ushare-management/
        System.out.println("dirPath = " + dirPath);
        //prefix = D:/Danei/
        String prefix = urlStr.substring(6, urlStr.indexOf("ushare-management"));
        System.out.println("prefix = " + prefix);
        dirPath += "articlePictures/";
        dirPath = prefix + dirPath;
        System.out.println("dirPath = " + dirPath);
        //dirPath = D:/Danei/ushare-management/articlePictures/

        //得到原始文件名
        String fileName = picFile.getOriginalFilename();
        System.out.println("fileName = " + fileName);
        //得到后缀名 从最后一个.出现的位置截取到最后
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //得到唯一文件名 UUID.randomUUID()得到一个唯一标识符
        fileName = UUID.randomUUID() + suffix;
        System.out.println("fileName = " + fileName);
        //准备保存图片的文件夹路径
        File dirFile = new File(dirPath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        //得到文件的完整路径
        String filePath = dirPath + "/" + fileName;
        System.out.println("filePath = " + filePath);
        //把文件保存到此路径
        picFile.transferTo(new File(filePath));
        return fileName;
    }

    //删除上传的图片
    @Override
    public void removePicture(String pictureName) {
        String filePath = dirPath + "/" + pictureName;
        new File(filePath).delete();
    }

    //得到文章封面
    public Article getArticleCover(String ruleForm) {
        ArticleAddNewDTO articleAddNewDTOs = convertedType(ruleForm);
        Article article = new Article();
        BeanUtils.copyProperties(articleAddNewDTOs, article);
        //默认用户上传的第一张图片为封面
        //得到用户发的第一张图片
        String firstPicture = articleAddNewDTOs.getArticlePictureAddDTO().get(0);
        System.out.println("firstPicture = " + firstPicture);
        //得到图片名
        String coverName = null;
        if (firstPicture.contains(",")) {
            coverName = firstPicture.substring(2, firstPicture.indexOf(",") - 1);
        } else {
            coverName = firstPicture.substring(2, firstPicture.lastIndexOf('"'));
        }
        System.out.println("cover = " + coverName);
        //得到图片路径
        String cover = "http://localhost:9092/articlePictures/" + coverName;
        System.out.println("cover = " + cover);
        //向数据库中添加文章
        article.setCover(cover);
        return article;
    }

    //将传过来的参数转换成自己想要的类型
    private ArticleAddNewDTO convertedType(String ruleForm) {
        System.out.println("ruleForm = " + ruleForm);
        JSONObject jsonObject = JSONObject.parseObject(ruleForm);
        ArticleAddNewDTO articleAddNewDTOs = JSON.toJavaObject(jsonObject, ArticleAddNewDTO.class);
        System.out.println("articleAddNewDTO = " + articleAddNewDTOs);
        return articleAddNewDTOs;
    }

    //得到要插入图片的路径
    public List<String> getPicturePath(String ruleForm) {
        String[] split = null;
        List<String> list = new ArrayList<>();
        ArticleAddNewDTO articleAddNewDTOs = convertedType(ruleForm);
        for (String url : articleAddNewDTOs.getArticlePictureAddDTO()) {
            System.out.println("url = " + url);
            String substring = url.substring(1, url.lastIndexOf(']'));
            System.out.println("substring = " + substring);
            split = substring.split(",");
        }
        for (int i = 0; i < split.length; i++) {
            String picturePath = split[i].substring(1, split[i].lastIndexOf('"'));
            System.out.println("picturePath = " + picturePath);
            picturePath = "http://localhost:9092/articlePictures/" + picturePath;
            System.out.println("picturePath = " + picturePath);
            list.add(picturePath);
        }
        return list;
    }


    @Override
    public Integer articleCountByTitle(String title) {
        return articleMapper.articleCountByTitle(title);
    }

    @Override
    public int addUserLoveCount(Integer userId) {
        return articleMapper.addUserLoveCount(userId);
    }

    @Override
    public int subUserLoveCount(Integer userId) {

        return articleMapper.subUserLoveCount(userId);
    }

    // 日志操作
    private String logOperation() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = (String) principal;
        return username;
    }

}

